<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.num" placeholder="推广号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="编号" prop="id" align="center" width="65"/>
      <el-table-column label="推广号" prop="rcNumber" align="center"/>
      <el-table-column label="员工姓名" prop="rcName" align="center"/>
      <el-table-column label="推广员类别" prop="rcType" align="center">
        <template slot-scope="scope">
          {{ ['驻厂员', '门店', '普通推广员'][scope.row.rcType] }}
        </template>
      </el-table-column>
      <el-table-column label="电话号码" prop="rcPhone" align="center"/>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleDetail(scope.row)">查看</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item :label-width="formLabelWidth" label="推广员类别">
          <el-select v-model="temp.rcType">
            <el-option key="0" :value="0" label="驻厂员">驻厂员</el-option>
            <el-option key="1" :value="1" label="门店">门店</el-option>
            <el-option key="2" :value="2" label="普通推广员">普通推广员</el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="推广员编号">
          <el-input v-model="temp.rcNumber" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="推广员姓名">
          <el-input v-model="temp.rcName" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="推广员手机号">
          <el-input v-model="temp.rcPhone" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogDetailFormVisible">
      <el-form ref="dataDetail" :rules="rules" :model="temp" label-position="right" label-width="100px">
        <el-form-item :label-width="formLabelWidth" label="员工工号">
          <span>{{ temp.rcNumber }}</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="推荐二维码">
          <img :src="temp.rcCode" style="width: 100px; height: 100px;">
          <!-- <el-button type="primary">下载二维码</el-button> -->
          <a :href="temp.rcCode" download="二维码">下载二维码</a>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="有效推广人数">
          <span>{{ tempTotal }}</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="被推广账号">
          <el-table v-loading="listLoading" :key="tableKey" :data="tempList" border fit highlight-current-row style="width: 100%;">
            <el-table-column label="编号" prop="id" align="center" width="65"/>
            <el-table-column label="昵称" prop="userNickName" align="center"/>
            <el-table-column label="关注时间" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="tempTotal" :page.sync="tempListQuery.page" :limit.sync="tempListQuery.limit" @pagination="getUsersList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

	<script>
		import {
	fetchPromotionAjax,
	addPromotionAjax,
	updatePromotionAjax,
	delPromotionAjax,
	getPromotionCodeAjax,
	getPromotionUsersAjax
} from "@/api/promotion";
import waves from "@/directive/waves"; // Waves directive
// import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

const calendarTypeOptions = [
{ key: "CN", display_name: "China" },
{ key: "US", display_name: "USA" },
{ key: "JP", display_name: "Japan" },
{ key: "EU", display_name: "Eurozone" }
];

// arr to obj ,such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
// 	acc[cur.key] = cur.display_name;
// 	return acc;
// }, {});

export default {
	name: "ComplexTable",
	components: { Pagination },
	directives: { waves },
	filters: {
	},

	data() {
		return {
			tableKey: 0,
			list: [],
			total: 0,
			tempTotal: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10
			},
			tempListQuery: {
				pageNum: 1,
				pageSize: 10
			},
			textMap: {
				create: "新增推广员",
				detail: '员工信息'
			},
			calendarTypeOptions,
			downloadLoading: false,
			dialogFormVisible: false,
			temp: {},
			formLabelWidth: '150px',
			rules: {},
			dialogStatus: '',
			dialogDetailFormVisible: false,
			tempList: []
		};
	},
	created() {
		this.getList();
	},
	methods: {
		getList() {
			this.listLoading = true;
			this.listLoading = false;
			this.listLoading = true;
			fetchPromotionAjax(this.listQuery).then(response => {
				// if (respons.data.data.) {

				// }
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				this.listLoading = false;
			});
		},

		handleFilter() {
			this.listQuery.page = 1;
			this.getList();
		},

		handleCreate() {
			// this.resetTemp();
			this.temp = {};
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].resetFields();
			});
		},

		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					addPromotionAjax(this.temp).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		handleUpdate(row) {
			this.temp = Object.assign({}, row); // copy obj
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const tempData = Object.assign({}, this.temp);
					delete tempData.rcCode;
					tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
					updatePromotionAjax(tempData).then(() => {
						// for (const v of this.list) {
						// 	if (v.id === this.temp.id) {
						// 		const index = this.list.indexOf(v);
						// 		this.list.splice(index, 1, this.temp);
						// 		break;
						// 	}
						// }
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
						this.getList();
					});
				}
			});
		},
		getUsersList(data) {
			getPromotionUsersAjax(data, this.tempListQuery).then(response => {
				this.tempList = response.data.data.pageData;
				this.tempTotal = response.data.data.maxCount;
			})
		},
		handleDetail(data) {
			this.dialogStatus = "detail";
			this.dialogDetailFormVisible = true;
			this.temp = data;
			getPromotionCodeAjax(data).then(data => {
				this.temp.rcCode = 'data:image/jpeg;base64,' + data.data.data;
			})
			this.getUsersList(data);
		},
		handleDelete(row) {
			this.$confirm('确认删除该条数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				delPromotionAjax(row).then((res) => {
				// const index = this.list.indexOf(row);
				// this.list.splice(index, 1);
				if (res.data.code !== 0 || res.data.data.length < 0) {
						this.$message({
							message: '删除失败',
							type: 'error',
							duration: 5 * 1000
						})
						return;
					}
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
					this.getList();
				});
			})
		}
	}
};
</script>
